<template>
  <div class="system-user-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1000px">
      <el-form ref="articleDialogFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="auto">
        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="所属机构" prop="orgId">
              <el-tree-select
                  v-model="state.ruleForm.orgId"
                  :data="props.orgTree??[]"
                  :render-after-expand="false"
                  style="width: 500px"
                  check-strictly
                  filterable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="所属栏目" prop="channelId">
              <el-tree-select
                  v-model="state.ruleForm.channelId"
                  :data="props.channelTree??[]"
                  :render-after-expand="true"
                  style="width: 500px"
                  check-strictly
                  filterable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="文章标题" prop="articleTitle">
              <el-input v-model="state.ruleForm.articleTitle"
                        placeholder="请输入文章标题"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="是否外部链接" prop="isExternalLink">
              <el-select v-model="state.ruleForm.isExternalLink" placeholder="请选择是否外部链接">
                <el-option label="否" value="0"></el-option>
                <el-option label="是" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35" v-show="state.ruleForm.isExternalLink==1">
          <el-col :span="24" class="mb20" >
            <el-form-item label="外部链接" prop="externalLink">
              <el-input v-model="state.ruleForm.externalLink" placeholder="请输入外部链接" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35" v-show="state.ruleForm.isExternalLink==0">
          <el-col :span="24" class="mb20">
            <el-form-item label="文章内容" prop="article">
              <Editor v-model:get-html="state.editor.htmlVal"
                      v-model:get-text="state.editor.textVal"
                      :disable="state.editor.disable"
                      :server="state.editor.server"
                      :videoServer="state.editor.videoServer"
                      :field-name="state.editor.fileName"
                      :max-file-size="state.editor.maxFileSize"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="排序优先级" prop="articlePriority">
              <el-input-number v-model="state.ruleForm.articlePriority" :min="1"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                  v-model="state.ruleForm.publishTime"
                  type="datetime"
                  placeholder="请选择发布时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  time-format="HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(articleDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="articleDialog">
import {nextTick, reactive, ref, defineAsyncComponent, watch} from 'vue';
import {systemApi} from "/@/api/system";
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {useArticleApi} from "/@/api/cms/article";
import {IEditorConfig} from "@wangeditor/editor";

const {add, edit} = useArticleApi();
const {orgTree} = systemApi();
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
// 定义属性，父传子
const props = defineProps(['orgId', 'orgTree', 'channelTree']);
const Editor = defineAsyncComponent(() => import('/@/components/editor/index.vue'));
// 定义变量内容
const articleDialogFormRef = ref();
const state = reactive({
  sysOrgData: [] as OrgTreeType[],
  ruleForm: {
    id: '',
    orgId: '',
    channelId: '',
    channelName: '',
    articleTitle: '',
    article: '',
    // 是否外部链接
    isExternalLink: 0,
    externalLink: '',
    articlePriority: 1,
    articleDisable: '',
    publishTime: '',
    tenantId: '',
    isDelete: ''
  },
  editor: {
    htmlVal: '',
    textVal: '',
    disable: false,
    server: 'https://www.slkjyun.cn/api/admin/file/editorUpload',
    videoServer: 'https://www.slkjyun.cn/api/admin/file/editorUploadVideo',
    fileName: 'file',
    maxFileSize: 1024 * 1024 * 1024
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  sysOrgTreeData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 2100,
    },
  }
});

const rules = reactive<FormRules<any>>({
  orgId: [
    {required: true, message: '请选择栏目所属机构', trigger: 'change'},
  ],
  channelId: [
    {required: true, message: '请选择栏目', trigger: 'change'},
  ],
  articleTitle: [
    {required: true, message: '文章标题不能为空', trigger: 'blur'},
    {min: 3, max: 30, message: '文章标题长度应该在3到30个字符之间', trigger: 'blur'},
  ],
  isExternalLink: [
    {required: true, message: '请选择是否外部链接', trigger: 'change'},
  ],
  article: [],
  externalLink: [],
  publishTime: [
    {required: true, message: '发布时间不能为空', trigger: 'blur'},
  ],
  articlePriority: [
    {required: true, message: '排序优先级不能为空'},
    {type: 'number', message: '排序优先级必须为数字'},
  ]
})

// 监听 isExternalLink 的变化，动态更新 rules
watch(() => state.ruleForm.isExternalLink, (newVal) => {
  if (newVal === '0') {
    rules.article = [
      {required: true, message: '文章内容不能为空', trigger: 'blur'}
    ];
    rules.externalLink = [];
  } else if (newVal === '1') {
    rules.externalLink = [
      {required: true, message: '外部链接不能为空', trigger: 'blur'}
    ];
    rules.article = [];
  }
});

// 从 UTC 转换为本地时间显示的方法
const convertToLocalTime = (utcTimeStr: string) => {
  const date = new Date(utcTimeStr);
  return date.toLocaleString().replaceAll(/\//g, '-');
}
// 打开弹窗
const openDialog = async (type: string, row: RowCmsArticleType) => {
  state.ruleForm.orgId = props.orgId;
  state.sysOrgData = props.orgTree;
  if (type === 'edit') {
    state.dialog.title = '修改文章';
    state.ruleForm = row;
    state.editor.htmlVal = row.article;
    if (state.ruleForm.publishTime) {
      state.ruleForm.publishTime = convertToLocalTime(row.publishTime);
    } else {
      state.ruleForm.publishTime = '';
    }
  } else {
    state.dialog.title = '新建文章';
    // 重置表单和编辑器状态
    clearForm()
  }

  // 根据 isExternalLink 的值初始化 rules
  if (state.ruleForm.isExternalLink === '0') {
    rules.article = [
      {required: true, message: '文章内容不能为空', trigger: 'blur'}
    ];
    rules.externalLink = [];
  } else if (state.ruleForm.isExternalLink === '1') {
    rules.externalLink = [
      {required: true, message: '外部链接不能为空', trigger: 'blur'}
    ];
    rules.article = [];
  }

  state.dialog.submitTxt = '保存并发布';
  state.dialog.isShowDialog = true;
};

const clearForm = () => {
  state.ruleForm = {
    id: '',
    orgId: '',
    channelId: '',
    channelName: '',
    articleTitle: '',
    article: '',
    articlePriority: 1,
    articleDisable: '',
    publishTime: '',
    tenantId: '',
    isDelete: ''
  }
  state.editor.htmlVal = '';
  state.editor.textVal = '';
}

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
  state.ruleForm.article = state.editor.htmlVal;
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      console.log('error submit!!', fields);
      ElMessage.error('数据校验失败!');
      return false;
    }
    // 根据 isExternalLink 的值动态调整 rules
    if (state.ruleForm.isExternalLink === 0) {
      rules.externalLink = [];
    } else {
      rules.article = [];
    }
    // TODO state.ruleForm.orgId = props.orgId;
    const res = state.ruleForm.id ? await edit(state.ruleForm) : await add(state.ruleForm)
    if (res.status === 200) {
      await nextTick(() => {
        if (articleDialogFormRef.value) {
          articleDialogFormRef.value.resetFields();
        }
      });
      ElMessage.success(state.ruleForm.id ? '保存成功' : '保存成功');
    }
    closeDialog();
    emit('refresh');
    // if (state.dialog.type === 'add') { }
  });
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>
<style scoped lang="scss">
.croppers-container {
  .cropper-img-warp {
    text-align: center;

    .cropper-img {
      margin: auto;
      width: 150px;
      height: 150px;
      border-radius: 100%;
    }
  }
}
</style>
